﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OfficeOpenXml;

namespace Bzzb.Controllers
{
    public class RenWuController : BaseController
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<RenWuController> _logger;
        private readonly IConfiguration _configuration;
        public RenWuController(ILogger<RenWuController> logger, IFreeSql fsql, IConfiguration configuration, IWebHostEnvironment env) : base(fsql)
        {
            this._env = env;
            this._logger = logger;
            this._configuration = configuration;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            ISelect<RenWu> iselect = _fsql.Select<RenWu>().WhereIf(begintime != DateTime.MinValue, rw => rw.Rq >= begintime).WhereIf(endtime != DateTime.MinValue, rw => rw.Rq <= endtime).OrderBy("id desc");
            List<RenWu> renwus;
            long total = -1;
            if (doPage == 0)
            {
                renwus = await iselect.ToListAsync();
            }
            else
            {
                renwus = await iselect.Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("data", renwus == null ? null : JArray.FromObject(renwus));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] RenWu renwu)
        {
            int affrows = 0;
            _fsql.Transaction(() => {
                long id = _fsql.Insert(renwu).ExecuteIdentity();
                _fsql.Update<RenWu>(id).Set(rw => rw.Number, DateTime.Now.ToString("yyyyMMdd") + id).ExecuteAffrows();
            });
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = 0;
            _fsql.Transaction(() => {
                _fsql.Delete<RenWu>().Where(rw => rw.Id == id).ExecuteAffrows();
                _fsql.Delete<XunJianShuJu>().Where(xjsj => xjsj.Rwid == id).ExecuteAffrows();
            });
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] RenWu renwu) {
            int affrows = await _fsql.Update<RenWu>().SetSource(renwu).ExecuteAffrowsAsync();

            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10) {
            ISelect<XunJianShuJu> iselect = _fsql.Select<XunJianShuJu>().Where(xjsj => xjsj.Rwid == id).OrderBy("id desc");
            List<XunJianShuJu> users;
            long total = -1;
            if (doPage == 0)
            {
                users = await iselect.ToListAsync();
            }
            else
            {
                users = await iselect.Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("data", users == null ? null : JArray.FromObject(users));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> ExportExcel([FromForm] long id)
        {
            RenWu renwu = await _fsql.Select<RenWu>().Where(rw => rw.Id == id).ToOneAsync();
            if (String.IsNullOrEmpty(renwu.Daan)) {
                return RenderJson(status: "failed", message: "导出出错", code: 2007, data: null);
            }
            List<Dictionary<string, string>> daan = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(renwu.Daan);

            string filePath = @"wwwroot/template/巡检（机炉电）输出.xlsx";
            FileInfo fileInfo = new(filePath);
            using (ExcelPackage excelPackage = new(fileInfo)) {
                for (int i = 0; i < daan.Count; i++)
                {
                    ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[i];
                    foreach (var item in daan[i])
                    {
                        worksheet.Cells[item.Key].Value = item.Value;
                    }
                }
                excelPackage.Save();
            }
            string pLocalFilePath = @"wwwroot/template/巡检（机炉电）输出.xlsx";//要复制的文件路径
            string pSaveFilePath = $"wwwroot/template/{renwu.Number}.xlsx";//指定存储的路径
            if (System.IO.File.Exists(pLocalFilePath))//必须判断要复制的文件是否存在
            {
                System.IO.File.Copy(pLocalFilePath, pSaveFilePath, true);//三个参数分别是源文件路径，存储路径，若存储路径有相同文件是否替换
            }
            JObject data = new();
            data.Add("url", _configuration.GetValue<string>("UploadUrl") + $"/template/{renwu.Number}.xlsx");
            return RenderJson(data: data);
        }
    }
}
